#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "pthread.h"
#include <signal.h>


pthread_mutex_t lock;   
pthread_mutex_t lock1; 
pthread_cond_t equal;  
pthread_cond_t equal1; 
static int i=7,j=6,z;

void *thread1(void *data)
{     
  
       while(j>=0){
           pthread_mutex_lock(&lock);
           if (j == 0) {
           printf("右侧通过! 左侧通行\n");
             sleep(1);	
           }
          
	   	
           if(i>0&&z==0)
           {
           
           pthread_cond_wait(&equal1,&lock);
     
	   }	
	   
           if (j >0) 
           {
           j--;
           z=1;
           sleep(1);
           }
	   printf("R: LEFT=%d,RIGHT=%d\n",i,j);
	   
	  
	   if(i==0&&j==0)
	   sleep(1);
           pthread_mutex_unlock(&lock); 
      }
           return NULL;
}
     

void *thread2(void *data)
{     
	while(i>=0){
	pthread_mutex_lock(&lock);
        if (i == 0) {
            
            printf("左侧通过! 右侧通行\n");
            pthread_cond_signal(&equal1);
            
            pthread_mutex_unlock(&lock);
            sleep(1);
          

        }
        if(j>0&&z==1)
        pthread_mutex_lock(&lock);
       
      	if(i>0)
      	{
           i--;
           z=0;
           sleep(1);
           }
	   printf("L: LEFT=%d,RIGHT=%d\n",i,j);
	   
	   if(i==0&&j==0)
	    sleep(1);
           pthread_mutex_unlock(&lock);
	
	
	}
	
}
	




void *thread3(void *data)
{
      int a,b;
      a=1;
      while(1){	
        pthread_mutex_lock(&lock);
        pthread_mutex_unlock(&lock);  
     
        a= rand()%10;
        b= rand()%10;
        if(a<=10){
        sleep(a);
        i=i+a;
        printf("左侧来车：%d\n",a);
        }
        if(b<=10){
        sleep(b);
        printf("右侧来车：%d\n",b);
        j=j+b;
        }
     }
      
}

int main(int argc,char *argv[])
{
	pthread_t th_left;
	pthread_t th_right;
	pthread_t th_a;

	void * retval;

	pthread_mutex_init(&lock,NULL);
	pthread_mutex_init(&lock1,NULL);
	pthread_cond_init(&equal,NULL);	
	pthread_cond_init(&equal1,NULL);
	pthread_create(&th_left, NULL, thread1, 0);
	pthread_create(&th_right, NULL, thread2, 0);
	pthread_create(&th_a, NULL, thread3, 0);	

          
       pthread_join(th_left, &retval);
       pthread_join(th_right, &retval);
       pthread_mutex_destroy(&lock);
       pthread_cond_destroy(&equal);
 
       return 0;
}
